import { useState, useEffect } from "react"
import {
  closestCenter,
  DndContext,
  DragOverlay,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors
} from "@dnd-kit/core"
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  verticalListSortingStrategy
} from "@dnd-kit/sortable"

import { SortableItem } from "./SortableItem"
import Item from "./Item"

function App() {
  const [activeId, setActiveId] = useState(null)
  const [items, setItems] = useState(["1", "2", "3"])
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    })
  )
  useEffect(() => {
    console.log("items交换位置or数据变化,提交", items)
  }, [items])

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
    >
      <SortableContext items={items} strategy={verticalListSortingStrategy}>
        {items.map(id => {
          if (id === activeId) {
            return (
              <div
                key={id}
                style={{
                  height: "100px",
                  backgroundColor: "#E0E2EE",
                  margin: "10px",
                  display: "flex",
                  justifyContent: "center",
                  alignItems: "center",
                  border: "1px dashed blue"
                }}
              >
                {activeId}
              </div>
            )
          }
          return (
            <SortableItem key={id} id={id}>
              <div>{id}</div>
            </SortableItem>
          )
        })}
      </SortableContext>
      <DragOverlay>
        {activeId ? (
          <Item id={activeId}>
            <div>{activeId}</div>
          </Item>
        ) : null}
      </DragOverlay>
    </DndContext>
  )

  function handleDragStart(event) {
    const { active } = event

    setActiveId(active.id)
  }

  function handleDragEnd(event) {
    const { active, over } = event

    if (active.id !== over.id) {
      setItems(items => {
        const oldIndex = items.indexOf(active.id)
        const newIndex = items.indexOf(over.id)

        return arrayMove(items, oldIndex, newIndex)
      })
    }

    setActiveId(null)
  }
}

export default App
